package com.zhiwang.xiaoqu.util

import android.app.ActivityManager
import android.app.AppOpsManager
import android.app.usage.UsageStatsManager
import android.content.Context
import android.os.Build
import android.util.Log


object AppDetector {

    val TAG = "AppDetector"

    var usageStatsManager: UsageStatsManager? = null

    var activityManager: ActivityManager? = null

    var prevAppPkgName = ""

    private fun hasAppUsageStatsPermission(context: Context): Boolean {

        val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager?
        var mode = 0

        mode = appOps!!.checkOpNoThrow(
            AppOpsManager.OPSTR_GET_USAGE_STATS,
            android.os.Process.myUid(), context.packageName
        )

        return mode == AppOpsManager.MODE_ALLOWED
    }

    fun hasAppUsagePermission(activity: Context): Boolean =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            hasAppUsageStatsPermission(activity)
        } else true

    fun queryAppUsage(context: Context, packageName: String): Boolean {

        val now = System.currentTimeMillis()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (usageStatsManager == null)
                usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager

            val queryUsageStats =
                usageStatsManager?.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 1000 * 5, now)

            queryUsageStats?.sortBy { it.lastTimeUsed }

            val lastApp = if (queryUsageStats?.isEmpty() != false) null else queryUsageStats.last()

            queryUsageStats?.forEach {
                Log.i(TAG, "queryAppUsage: ${it.lastTimeUsed} ${it.packageName}")
            }

            Log.i(TAG, "queryAppUsage:----Last ${lastApp?.packageName}   Prev: --${prevAppPkgName}")
            lastApp?.apply {
                prevAppPkgName = this.packageName
            }
            //目标 app 使用一段时间后，没有应用的切换，查询到的 列表为空， lastApp  = null ；所以记录之前的包名
            return if (lastApp == null) prevAppPkgName == packageName else lastApp.packageName === packageName
        } else {
            if (activityManager == null)
                activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

            val runningTasks = activityManager?.getRunningTasks(20)

            val first = runningTasks?.first()
            return first != null && first.topActivity.packageName == packageName
        }


    }

}